package com.fyzk.activity.lottery.jc.football.newJz.data;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.DataUtil.md5.MD5;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import http.XRequestCallBack;

//import com.lidroid.xutils.HttpUtils;
//import com.lidroid.xutils.exception.HttpException;
//import com.lidroid.xutils.http.RequestParams;
//import com.lidroid.xutils.http.ResponseInfo;
//import com.lidroid.xutils.http.client.HttpRequest;

/**
 * Created by fanxs11 on 16/5/2.
 *
 * 足球数据概述view
 */
public class FootballMatchSummaryView extends LinearLayout {

    private Context context;

    private String matchNum = "20160511001";

    private TextView lspm;
    private TextView lsjf;
    private TextView lsjf_s;
    private TextView lsjf_p;
    private TextView lsjf_f;
    private TextView jqzj;
    private TextView pl3;
    private TextView pl1;
    private TextView pl0;


    public FootballMatchSummaryView(Context context, AttributeSet attrs, int defStyle, String matchNum) {
        super(context, attrs, defStyle);
        this.context = context;
        this.matchNum = matchNum;
        queryGameRequest();
        initView();
    }

    public FootballMatchSummaryView(Context context, AttributeSet attrs, String matchNum) {
        this(context, attrs, 0, matchNum);
    }

    public FootballMatchSummaryView(Context context, String matchNum) {
        this(context, null, matchNum);
    }

    public void initView(){
        View.inflate(context, R.layout.jc_footballmatchsummary_view, this);

        lspm = (TextView) findViewById(R.id.footballmatchsummary_lspm);
        lsjf = (TextView) findViewById(R.id.footballmatchsummary_lsjf_tv1);
		lsjf_s = (TextView) findViewById(R.id.footballmatchsummary_lsjf_tv2);
		lsjf_p = (TextView) findViewById(R.id.footballmatchsummary_lsjf_tv3);
		lsjf_f = (TextView) findViewById(R.id.footballmatchsummary_lsjf_tv4);
		jqzj = (TextView) findViewById(R.id.footballmatchsummary_jqzj);
		pl3 = (TextView) findViewById(R.id.footballmatchsummary_pl3);
		pl1 = (TextView) findViewById(R.id.footballmatchsummary_pl1);
		pl0 = (TextView) findViewById(R.id.footballmatchsummary_pl0);
    }

    /* 查询对阵信息请求 */
    private void queryGameRequest() {
        try {
            JSONObject request = new JSONObject();
            request.put("matchNum", matchNum);
            httpPostJson(CommandUtil.FOOTBALLMATCHSUMMARY, getCommand(), request, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected String getCommand() {
        return Commands.FOOTBALLMATCHSUMMARY;
    }

    JCZQ_MatchSummaryResponse response;

    public void onSuccess(int requestCode,
                             StringResultBean resultBean, String result) {
        switch (requestCode) {
            case CommandUtil.FOOTBALLMATCHSUMMARY:
                response = JSON.parseObject(resultBean.getData(), JCZQ_MatchSummaryResponse.class);

                String homeTeamRanking = "(无)";
                String awayTeamRanking = "(无)";
                if (response.getHomeTeamRanking() != null) {
                    homeTeamRanking = response.getHomeTeamRanking();
                }
                if (response.getAwayTeamRanking() != null) {
                    awayTeamRanking = response.getAwayTeamRanking();
                }
                lspm.setText(response.getHomeTeam()+":"+homeTeamRanking+"  "+response.getAwayTeam()+":"+awayTeamRanking);

                lsjf.setText("近"+response.getHistoryTotal()+"次交战，"+response.getHomeTeam());
                lsjf_s.setText(response.getHistory3()+"胜");
                lsjf_p.setText(response.getHistory1()+"平");
                lsjf_f.setText(response.getHistory0()+"负");

                jqzj.setText("主队 "+response.getHomeTotal3()+"胜 "+response.getHomeTotal1()+"平 "+response.getHomeTotal0()+"负, "+
                        "客队 "+response.getAwayTotal3()+"胜 "+response.getAwayTotal1()+"平 "+response.getAwayTotal0()+"负");
                pl3.setText(response.getAvgh());
                pl1.setText(response.getAvgs());
                pl0.setText(response.getAvga());
                Log.i("response", "response: " + result);
                break;
            default:
                break;
        }
    }

    public void onFailure(int requestCode, String errorcode, String msg) {
        AppToast.getToast().show(msg);
    }

    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress) {
        sendRequestUseJson(HttpMethod.POST, requestCode, command, params, showProgress);
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJson(HttpMethod method, int requestCode, String command,
                                   JSONObject params2, final boolean showProgress) {


        if (!AppUtil.isNetworkAvailable()) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
//			showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                onFailure(getRequestCode(), "网络异常");
                if (showProgress) {
//					cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String netResult = null;
                String decode_ = null;
                try {
                    decode_ = ToolsAesCrypt.Decrypt(result.substring(1, result.length() - 1),
                            UrlDef.stringFromJNI());
                    System.out.println("decode>" + decode_);
                    byte[] base64d = com.fyzk.utils.Base64.decode(decode_);
                    byte[] decompress = PublicMethod.decompress2(base64d);
                    netResult = new String(decompress, "utf-8");

                    LogUtil.d("联网：解密后返回>" + netResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    StringResultBean resultBean = JSON.parseObject(netResult,
                            StringResultBean.class);
                    if (resultBean.getErrorcode().equals("0")) {
                        FootballMatchSummaryView.this.onSuccess(getRequestCode(), resultBean,
                                netResult);
                    } else {
                        FootballMatchSummaryView.this.onFailure(getRequestCode(), resultBean.getErrorcode(),resultBean.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    FootballMatchSummaryView.this.onSuccess(getRequestCode(), null,
                            netResult);
                }
                if (showProgress) {
//					cancelProgressDialog();
                }

            }
        };

        RequestParams params = new RequestParams(UrlDef.TY_URL_NEW_DATA2);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();

            String hah = MD5.toMd5((UrlDef.stringFromJNI() + timestamp).getBytes("UTF-8"));

            String token = http.DataUtil.md5.MD5.toMd5(hah.getBytes("UTF-8"));
            LogUtil.d("token>>>"+token);

            String agent = "";
            try {
                ApplicationInfo appInfo = App.getContext().getPackageManager().getApplicationInfo(
                        App.getContext().getPackageName(), PackageManager.GET_META_DATA);
                agent = appInfo.metaData.getString("UMENG_CHANNEL");
            } catch (PackageManager.NameNotFoundException e1) {
                // TODO Auto-generated catch block
                agent = "gw";
                e1.printStackTrace();
            }
            clientInfo.put("agentId", agent);
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionCode());
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：发送请求>" + encrypt);
            params.addBodyParameter("body", encrypt);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }


//    /**
//     * 取消提示dialog显示
//     */
//    public void cancelProgressDialog() {
//        if (progressDg != null && progressDg.isShowing()) {
//            progressDg.cancel();
//        }
//    }
//
//    /**
//     * 显示提示
//     */
//    public void showProgressDialog() {
//        if (!isFinishing()) {
//            if (progressDg == null || !progressDg.isShowing()) {
//                progressDg = CustomProgress.show(this, null, false, null);
//            }
//        }
//    }


    protected void onFailure(int requestCode,String msg) {
        if(TextUtil.isEmpty(msg)){
            AppToast.getToast().show("网络异常");
        }else{
            AppToast.getToast().show(msg);
        }
    }


}
